import com.adobe.serialization.json.JSON;

import flash.events.Event;
import flash.events.LocationChangeEvent;
import flash.events.MouseEvent;
import flash.events.ProgressEvent;
import flash.events.TransformGestureEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.navigateToURL;
import flash.system.Capabilities;

import mx.collections.ArrayCollection;
import mx.collections.XMLListCollection;
import mx.events.FlexEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.ObjectUtil;

import spark.effects.Fade;



private var xmlcol_rankedMovieList:XMLListCollection;
private var fullData:Object;
protected function getRankedMovieList_resultHandler(event:ResultEvent):void
{
	// TODO Auto-generated method stub
	//xmlcol_rankedMovieList = new XMLListCollection( new XMLList(event.result.data) );
	//trace(ObjectUtil.toString(xmlcol_rankedMovieList));
	var dataObj:Object = new Object();
	dataObj = event.result.data.movie;
	fullData = dataObj;
	
	//trace(ObjectUtil.toString(dataObj.movie[0]));
	
	downAllBrochure();
	
	brochure.setData(dataObj, -1);
	
	dataObj = null;
}

private function downAllBrochure():void{
	//progress.play();
	for(var i:int=0; i<fullData.length; i++){
		downBrochure(i);
	}
	//progress.stop();
}

public var imgLoader:URLLoader = new URLLoader();
private var fileStream:FileStream;
private var encodedFileName:String;
private var urlEncodeForwardSlashedRegExp:RegExp;
private var tilefile:File;
private function downBrochure(index:int):void{
	
	
	fileStream = new FileStream();
	
	encodedFileName = encodeURI(escape(fullData[index].poster_url));
	
	urlEncodeForwardSlashedRegExp = new RegExp("/", "gi");
	encodedFileName = encodedFileName.replace(urlEncodeForwardSlashedRegExp, "%2F");
	
	/*
	if(deviceInfo_os_name == 'iOS'){
	var cacheDir:File = new File(File.applicationDirectory.nativePath + "/\.\./Library/Caches");
	tilefile = cacheDir.resolvePath(encodedFileName);
	}else if(deviceInfo_os_name == 'AND'){
	tilefile = File.applicationStorageDirectory.resolvePath(encodedFileName);
	}
	*/
	
	tilefile = File.applicationStorageDirectory.resolvePath(encodedFileName);
	
	trace("downloading brochure : " + tilefile.url);
	
	if (tilefile.exists) {
		trace(encodedFileName + " is exist.");
		fileStream.open(tilefile, FileMode.READ);
		fileStream.close();
		
	}else{
		
		trace(encodedFileName + " is not exist.");
		imgLoader.dataFormat = URLLoaderDataFormat.BINARY;
		imgLoader.load(new URLRequest(fullData[index].poster_url));
		imgLoader.addEventListener(Event.COMPLETE, saveBrochure);
		
	}
}

private function saveBrochure(event:Event):void{
	fileStream.open(tilefile, FileMode.WRITE);
	fileStream.writeBytes(imgLoader.data);
	fileStream.close();
	
	trace(tilefile.url + " was saved.");
}



protected function getRankedMovieList_faultHandler(event:FaultEvent):void
{
	// TODO Auto-generated method stub
	trace('http service was faulted'+event.toString());
	
}

public var deviceInfo_os_name:String;
protected function initProcess(event:FlexEvent):void
{
	// TODO Auto-generated method stub
	getRankedMovieList.send();
	
	list_movieTalk.visible = false;
	
	//this.addEventListener('BOTTOM_BAR_CLOSING', onBottomBarClosing);
	
	
	switch(true){
		case (Capabilities.version.indexOf('IOS') > -1):
			deviceInfo_os_name = "iOS"; 
			break;
		case (Capabilities.version.indexOf('QNX') > -1):
			deviceInfo_os_name = "BB"; // blackberry
			break;
		case (Capabilities.version.indexOf('AND') > -1):
			deviceInfo_os_name = "Android";
			break;
		default:
			deviceInfo_os_name = "Unknown";
			break;
	}
	
}

/*
private function onBottomBarClosing():void{
	spac_backBottom.height = 0;
}
*/

protected function onClickPoster(event:MouseEvent):void
{
	// TODO Auto-generated method stub
	brochure.onClickPoster();
}

private var btnFade:Fade = new Fade;
protected function onClickFlipRight():void
{
	// TODO Auto-generated method stub
	if(brochure._index + 1 <= brochure.maxLength - 1){
		brochure.setData(brochure.infoList, brochure._index + 1);
		
	}else{
		brochure.setData(brochure.infoList, 0);
		
	}
	btnFade.alphaFrom = 0.1;
	btnFade.alphaTo = 0.5;
	btnFade.duration = 1000;
	btnFade.play([img_flipRight]);
}

protected function onClickFlipLeft():void
{
	// TODO Auto-generated method stub
	if(brochure._index - 1 >= 0){
		brochure.setData(brochure.infoList, brochure._index - 1);
		
	}else{
		brochure.setData(brochure.infoList, brochure.maxLength - 1);
	}
	btnFade.alphaFrom = 0.1;
	btnFade.alphaTo = 0.5;
	btnFade.duration = 1000;
	btnFade.play([img_flipLeft]);
}

/*
protected function onGestureSwipe(event:TransformGestureEvent):void
{
	// TODO Auto-generated method stub
	// Swipe was to the right
	if (event.offsetX == 1 ) {
		onClickFlipLeft();
	}
		// Swipe was to the left
	else if (event.offsetX == -1 ) {
		// push the NextView withour any data using 
		onClickFlipRight();
	}
}
*/

protected function onClickShowMovieTalk(event:MouseEvent):void
{
	// TODO Auto-generated method stub
	if(list_movieTalk.visible){
		list_movieTalk.visible = false;
	}else{
		
		
		
		var param:Object = new Object();
		param.movie_id = brochure.info.movie_id;
		getMovieTalk.send(param);
		//progress.play();
	}
	
	
}

private var movieTalkList:ArrayCollection = new ArrayCollection();
protected function getMovieTalk_resultHandler(event:ResultEvent):void
{
	// TODO Auto-generated method stub
	
	var dataObj:Object = new Object();
	if( event.result.data != null ){
		dataObj = event.result.data.movie_talk;
		
		movieTalkList.removeAll();
		
		for(var i:int = 0; i<dataObj.length; i++){
			movieTalkList.addItem(dataObj[i]);
		}
		
		list_movieTalk.dataProvider = movieTalkList;
		
		//progress.stop();
		
		list_movieTalk.visible = true;
		
		/*
		var eff:Fade = new Fade();
		eff.alphaFrom = 0;
		eff.alphaTo = 1;
		eff.duration = 500;
		eff.target = list_movieTalk;
		
		eff.play();
		*/
	}
}

protected function getMovieTalk_faultHandler(event:FaultEvent):void
{
	// TODO Auto-generated method stub
	trace("getting movie talk list was fail : " + event.toString());
	//progress.stop();
}

public function setTitle(title:String):void{
	lab_title.text = title;
}

public function setRating(rating:String):void{
	lab_rating.text = rating;
	img_star.source = 'assets/star/star_' + Math.round(int(rating)).toString() + '.png';
}

private function convertRating():void{
	
}

public function goWebViewFront():void{
	if(this.currentState == 'webview'){
		webView.historyForward();
	}
}

public function goWebViewBack():void{
	if(this.currentState == 'webview'){
		webView.historyBack();
	}
}

protected function webViewInit(event:FlexEvent):void
{
	// TODO Auto-generated method stub
	trace("web view was created.");
	webView.addEventListener(ProgressEvent.PROGRESS, webViewProgressHandler);
}

private function webViewProgressHandler(event:ProgressEvent):void{
	trace((event.bytesLoaded/event.bytesTotal) * 100);
}

protected function onLocationChanging(event:LocationChangeEvent):void
{
	// TODO Auto-generated method stub
	
	if(event.location.toString().substr(0, "kakaolink:".length) == "kakaolink:"){
		event.preventDefault(); 
		navigateToURL( new URLRequest( event.location ) ); 
	}else{
		//progress.play();
	}
}

protected function onLocationChanged(event:LocationChangeEvent):void
{
	// TODO Auto-generated method stub
	
	//progress.stop();
}